package com.jhd.fuzhou.view.special;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.view.login.FuzhouApplication;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.SearchUnit;
import com.jhd.fuzhou.vo.SupervisionInspectionVo;

import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class SpecialChooseCompanyActivity extends BaseActivity {
    private Context context= this;
    private String data="";
    @BindView(R.id.rv_company)
    RecyclerView rv_company;
    @BindView(R.id.et_search)
    EditText et_search;
    @BindView(R.id.iv_cancel)
    ImageView iv_cancel;
    private SearchUnit searchUnit;
    @BindView(R.id.tv_loading)
    TextView tv_loading;//
    private UnitAdapter unitAdapter;
    private List<SupervisionInspectionVo> supervisionInspectionVoList=new ArrayList<>();

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_choose_company);
    }
    @Override
    protected void processLogic() {
        application.addStepActivity(this);
        searchUnit=new SearchUnit();
        searchUnit.setPageIndex(1);
        searchUnit.setPageNum(1);
        searchUnit.setKeyword(et_search.getText().toString());
        getSupervisedUnitList();
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        rv_company.setLayoutManager(layoutManager);
        rv_company.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition();
                if(lastCompletelyVisibleItemPosition==layoutManager.getItemCount()-1){
                    tv_loading.setVisibility(View.VISIBLE);
                    searchUnit.setPageIndex(searchUnit.getPageIndex()+1);
                    if(searchUnit.getPageIndex()<=searchUnit.getPageNum()){
                        tv_loading.setText(getString(R.string.loading));
                        getSupervisedUnitList();
                    }else{
                        tv_loading.setText(getString(R.string.arrival_bottom));
                    }
                }else{
                    tv_loading.setVisibility(View.GONE);//没到底部，隐藏
                }
            }
        });
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                searchUnit.setPageIndex(1);
                searchUnit.setKeyword(et_search.getText().toString());
                supervisionInspectionVoList.clear();
                getSupervisedUnitList();
                return false;
            }
        });
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().equals("")){
                    searchUnit.setPageIndex(1);
                    searchUnit.setKeyword(s.toString());
                    supervisionInspectionVoList.clear();
                    getSupervisedUnitList();
                    iv_cancel.setVisibility(View.GONE);
                }else{
                    iv_cancel.setVisibility(View.VISIBLE);
                }
            }
        });
    }
    @OnClick({R.id.iv_back,R.id.iv_cancel})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.iv_back:
                onBack();
                break;
            case R.id.iv_cancel://点击清空输入框，并隐藏取消按钮
                et_search.setText("");
                iv_cancel.setVisibility(View.GONE);
                break;
        }
    }
    public void getSupervisedUnitList() {
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
//        Retrofit retrofit = UtilHelper.retrofit(application, "http://192.168.1.69:9004/");//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, Object> params =  new LinkedHashMap<String, Object>();
        params.put("pageIndex", searchUnit.getPageIndex());
        params.put("pageSize",20);
        params.put("keyword",searchUnit.getKeyword());//模糊查询
        if(application.getOrgId()!=null)params.put("superviseOrgId",application.getOrgId());
        Call<JsonForResult> jsonForResultCall = vs.getSupervisedUnitList(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if (jsonForResult.getData() != null) {
                            List<SupervisionInspectionVo> supervisionInspectionVos = JSON.parseArray(jsonForResult.getData().toString(), SupervisionInspectionVo.class);
                            for (SupervisionInspectionVo supervisionInspectionVo : supervisionInspectionVos) {
                                supervisionInspectionVoList.add(supervisionInspectionVo);
                            }
                            if (searchUnit.getPageIndex() == 1) {
                                unitAdapter = new UnitAdapter();
                                rv_company.setAdapter(unitAdapter);
                            } else {
                                tv_loading.setVisibility(View.GONE);
                                unitAdapter.notifyDataSetChanged();
                            }
                            searchUnit.setPageNum(jsonForResult.getTotal()/20+1);
                        } else {
                            unitAdapter = new UnitAdapter();
                            rv_company.setAdapter(unitAdapter);
                            tv_loading.setText(context.getString(R.string.arrival_bottom));
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
//                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public class UnitAdapter extends RecyclerView.Adapter<UnitAdapter.ViewHolder> {
        @Override
        public UnitAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_company_special, parent, false);
            UnitAdapter.ViewHolder viewHolder = new UnitAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull UnitAdapter.ViewHolder holder, int position) {
            holder.tv_legalRepresentative.setText(StringUtil.isNullOrEmpty(supervisionInspectionVoList.get(position).getLegalRepresentative())?"":supervisionInspectionVoList.get(position).getLegalRepresentative());
            holder.tv_taskName.setText(StringUtil.isNullOrEmpty(supervisionInspectionVoList.get(position).getTaskName())?"":supervisionInspectionVoList.get(position).getTaskName());
            holder.tv_speciality.setText(supervisionInspectionVoList.get(position).getSpecialityCategory() + " - " + supervisionInspectionVoList.get(position).getSpecialityDetail());
            if (supervisionInspectionVoList.get(position).getRegisterAddress() != null) {
                holder.unitAddress.setText(supervisionInspectionVoList.get(position).getRegisterAddress());
            } else {
                holder.unitAddress.setText((StringUtil.isNullOrEmpty(supervisionInspectionVoList.get(position).getRegisterProvince())?"":supervisionInspectionVoList.get(position).getRegisterProvince())
                        + (StringUtil.isNullOrEmpty(supervisionInspectionVoList.get(position).getRegisterCity())?"":supervisionInspectionVoList.get(position).getRegisterCity()));
            }
            holder.tv_unitName.setText(supervisionInspectionVoList.get(position).getUnitName());
            holder.linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, SpecialCompanyDetailActivity.class);
                    //加入参数，传递给AnotherActivity
                    Gson gson = new Gson();
                    intent.putExtra("data", gson.toJson(supervisionInspectionVoList.get(position)));
                    startActivity(intent);
                }
            });
            holder.btn_add_report.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    //加入参数，传递给AnotherActivity
                    Gson gson = new Gson();
                    intent.putExtra("id", gson.toJson(supervisionInspectionVoList.get(position)));
                    //设置返回数据
                    ((Activity)context).setResult(1, intent);
                    ((Activity)context).finish();
                }
            });
            if("1".equals(supervisionInspectionVoList.get(position).getSpecialTaskStatus())){//填报
                if("0".equals(supervisionInspectionVoList.get(position).getInspectResult())){//不合格
                    holder.iv_status.setBackgroundResource(R.mipmap.ic_unqualified);
                }else if("1".equals(supervisionInspectionVoList.get(position).getInspectResult())){//合格
                    holder.iv_status.setBackgroundResource(R.mipmap.ic_qualified);
                }
            }else if("0".equals(supervisionInspectionVoList.get(position).getSpecialTaskStatus())){
                holder.iv_status.setBackgroundResource(R.mipmap.ic_report_no);
            }
        }

        @Override
        public int getItemCount() {
            return supervisionInspectionVoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_legalRepresentative, tv_speciality, unitAddress, tv_unitName,tv_taskName; //法人，所属专业，地址,被检测单位
            ImageView iv_status; //等级
            Button btn_add_report;
            LinearLayout linearLayout;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_legalRepresentative = itemView.findViewById(R.id.tv_legalRepresentative);
                this.tv_speciality = itemView.findViewById(R.id.tv_speciality);
                this.unitAddress = itemView.findViewById(R.id.unitAddress);
                this.tv_unitName = itemView.findViewById(R.id.tv_unitName);
                this.tv_taskName = itemView.findViewById(R.id.tv_taskName);
                this.iv_status = itemView.findViewById(R.id.iv_status);
                this.btn_add_report = itemView.findViewById(R.id.btn_add_report);
                this.linearLayout = itemView.findViewById(R.id.linearLayout);
            }
        }
    }

    public void onBack(){
        Intent intent = new Intent();
        intent.putExtra("id", "");
        //设置返回数据
        ((Activity)context).setResult(1, intent);
        ((Activity)context).finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}